
#! /usr/bin/python

import sys
import os
import time
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('../../../')
from spade import *
class Example(Agent.Agent):
    def _setup(self):
        entry = "Starting Organization Behaviour"
        self.info=[{"tipo":"Italiano","Calle":"lacalleDel C ", "nombre":"elnombre"}]




    def _process(self):
     pass
class MyOrganization(Federation.Federation):
    def _process(self):
        #u=MyUnit(agent=self.myAgent, nick="gestor", name="supervision")
        #self.addUnit(u)
        time.sleep(2000)



class MyUnit(Unit.Hierarchy):
    def _process(self):
        time.sleep(300)
        """
        mens=ACLMessage.ACLMessage()
        mens.setPerformative("request")
        mens.setSender(self.myAgent.getAID())
        aid=AID.aid("pepe@perez",["xmpp://pepe@perez"])
        mens.addReceiver(aid)
        mens.setContent("Trabajo??")
        time.sleep(20)
        print "Solicitamos"+str(mens)
        m=self.getMemberList()
        print m
        for i in m:
            self.sendPrivateMessage(i,mens)
            #self.sendMessage(mens)
        print self.receiveMessage()
        time.sleep(100)
        for i in m:
            self.kickAgent(i)
        """

    def creationPermissionTest(self,sender,desc=None):
       return False
    def entryUnitTest(self,sender,desc=None):
      d=desc
      if d.has_key("ofrece"):
           if str(d["ofrece"])=="fuentes de informacion":
               return True
      return False
    def askMembers(self,about):
        members=self.getMemberList()
        for m in members:
            mens=ACLMessage.ACLMessage()
            mens.setPerformative("request")
            mens.setSender(self.myAgent.getAID())
            aid=AID.aid(m,["xmpp://"+m])
            mens.addReceiver(aid)
            mens.setOntology("Restaurant")
            mens.setContent(about)
            print "Solicitamos"+str(mens)
            self.sendPrivateMessage(i,m)
        time.sleep(100)
        mens=self.receiveMessage()
        while mens:
            print "Recibimos"
            mens
            mens=self.receiveMessage()




if __name__ == "__main__":
    agent = "sitec@apolo.dsic.upv.es"
    #agent = "agent@thx1138.dsic.upv.es"
    #agent = "agent@tatooine.dsic.upv.es"
    b = Example(agent,"pasword")
    b.start()
    print "Agent "+agent+" registering"
    time.sleep(10)
    lista= b.getOrganizationList()
    for i in lista:
        info=b.getOrganizationInfo(i)
        if info.has_key("goal"):
            goal=info["goal"]
            g=eval(goal)
            if g.has_key("necesita") and "fuentes de reservas" in g["necesita"]:
                o=MyOrganization(b,nick="fuenteC", name=i)
                b.joinOrganization(o)
                time.sleep(20)
                l=o.getUnitList()
                for u in l:
                    info=o.getUnitInfo(u)
                    if info["type"]=="Hierarchy" and "fuentes de reservas" in eval(info["goal"])["necesita"]:
                        m=MyUnit(b, nick="reservasC.py", password="pass",name=u)
                        try:
                            o.joinUnit(m)
                        except Unit.MembersOnly:
                            print "Excepcion:MembersOnly"
                            d={"ofrece":"fuentes de reservas"}
                            entry=o.requestEntryUnit(u,d)
                            if entry:
                                    m=MyUnit(b, nick="resrvasC", password=entry,name=u)
                                    o.joinUnit(m)
                                    mens=m.receiveMessage()
                                    while not mens:
                                        mens=m.receiveMessage()
                                    print mens
                                    content=[]
                                    for i in b.info:
                                        if i["tipo"]==eval(mens.getContent())[0]["tipo"]:
                                            content.append(i)
                                    ans=ACLMessage.ACLMessage()
                                    ans.setPerformative("inform")
                                    ans.setSender(b.getAID())
                                    ans.addReceiver(mens.getSender())
                                    ans.setContent(str(content))
                                    print ans
                                    m.sendPrivateMessage(ans,mens.getSender().getName())

